package com.wuyan.locationdog.ui.device


import android.Manifest
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.viewModels
import com.arcsoft.commonbase.R
import com.arcsoft.commonbase.base.BaseBindingActivity
import com.arcsoft.commonbase.bean.DogFileBeanContent
import com.arcsoft.commonbase.bus.Bus
import com.arcsoft.commonbase.bus.bus_dog_file_info
import com.arcsoft.commonbase.bus.bus_toast
import com.arcsoft.commonbase.ext.afterTextChangeCoroutineDebounceListener
import com.arcsoft.commonbase.ext.customShowLong
import com.arcsoft.commonbase.ext.gone
import com.arcsoft.commonbase.ext.isTrimEmpty
import com.arcsoft.commonbase.ext.loadImageCircleCar
import com.arcsoft.commonbase.ext.textStringTrim
import com.arcsoft.commonbase.ext.visible
import com.arcsoft.commonbase.widgets.dialog.ToastBean
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.wuyan.locationdog.databinding.DeviceAddActivityBinding
import com.wuyan.locationdog.help.DogHelp
import com.wuyan.locationdog.help.LoginHelp
import com.wuyan.locationdog.viewmodel.DeviceViewModel
import com.yzq.zxinglibrary.android.CaptureActivity
import com.yzq.zxinglibrary.bean.ZxingConfig
import com.yzq.zxinglibrary.common.Constant

class DeviceAddActivity : BaseBindingActivity<DeviceAddActivityBinding>(), TextWatcher {

    private var firstBean: DogFileBeanContent? = null
    private var isFromLogin: Boolean = false
    private var dogId: String = ""
    private val mViewModel: DeviceViewModel by viewModels()

    override fun initData() {
        val scanText = intent.getStringExtra("scanText")
        isFromLogin = intent.getBooleanExtra("isFromLogin", false)

        setTitleText("添加设备")

        binding.apply {
            if (isFromLogin) {
                LoginHelp.isFromLogin = true
                btnScan.gone()
            }
            if (!scanText.isNullOrEmpty()) {
                etDeviceCode.setText(scanText)
                val map = HashMap<String, Any>()
                map["imei"] = etDeviceCode.textStringTrim()
                mViewModel.getCardNo(map)
            }
            etDeviceCode.addTextChangedListener(this@DeviceAddActivity)
            etPwd.addTextChangedListener(this@DeviceAddActivity)

            btnSure.setOnClickListener {
                if (isFromLogin) {
                    firstBean?.let {
                        val map = HashMap<String, Any>()
                        map["deviceId"] = SPUtils.getInstance().getString("deviceId", "")
                        map["devicePwd"] = etPwd.textStringTrim()
                        map["deviceName"] = etDeviceCode.textStringTrim()

                        map["dogName"] = it.dogName
                        map["age"] = it.age
                        map["dogType"] = it.dogType
                        map["gender"] = it.gender
                        map["weight"] = it.weight?:""
                        map["remark"] = it.remark
                        map["dogImg"] = it.dogImg.toString()
                        mViewModel.firstBindDog(map)
                    }
                    return@setOnClickListener
                }
                val map = HashMap<String, Any>()
                map["imei"] = etDeviceCode.textStringTrim()
                map["deviceName"] = etDeviceCode.textStringTrim()
                map["devicePwd"] = etPwd.textStringTrim()
                map["dogId"] = dogId
                mViewModel.addDevice(map)
            }

            btnScan.setOnClickListener {
                PermissionUtils.permission(Manifest.permission.CAMERA)
                    .callback { isAllGranted, granted, deniedForever, denied ->
                        if (isAllGranted) {
                            goCaptureActivity()
                        } else {
                            customShowLong("请打开相机权限")
                        }
                    }
                    .request()

            }

            btnAddDogInfo.setOnClickListener {
                if (LoginHelp.isDeviceLogin) {
                    DogHelp.isModifyDogFile = firstBean != null
                    DogHelp.mDogFileBeanContent = firstBean
                    ActivityUtils.startActivity(DogAddFilesActivity::class.java)
                    return@setOnClickListener
                }
                DogHelp.isGoDetail = false
                ActivityUtils.startActivity(DogFilesListActivity::class.java)

            }

            btnDogInfo.setOnClickListener {
                btnAddDogInfo.callOnClick()
            }


            etDeviceCode.afterTextChangeCoroutineDebounceListener {
                if (etDeviceCode.textStringTrim().isNullOrEmpty()) {
                    binding.cardNo.text = ""
                    return@afterTextChangeCoroutineDebounceListener
                }

                val map = HashMap<String, Any>()
                map["imei"] = etDeviceCode.textStringTrim()
                mViewModel.getCardNo(map)
            }
        }


    }

    private fun goCaptureActivity() {
        val intent = Intent(mActivity, CaptureActivity::class.java)
        val config = ZxingConfig()
        config.reactColor = R.color.text_color_selected //设置扫描框四个角的颜色 默认为白色
        config.scanLineColor = R.color.text_color_selected //设置扫描线的颜色 默认白色
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config)
        startActivityForResult(intent, 1111)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 扫描二维码/条码回传
        if (requestCode == 1111 && resultCode == RESULT_OK) {
            if (data != null) {
                val content = data.getStringExtra(Constant.CODED_CONTENT)
                binding.etDeviceCode.setText(content)
            }
        }
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun afterTextChanged(p0: Editable?) {
        binding.apply {
            if (etDeviceCode.isTrimEmpty() || etPwd.isTrimEmpty() || cardNo.isTrimEmpty()) {
                btnSure.alpha = 0.4F
                btnSure.isEnabled = false
            } else {
                btnSure.alpha = 1F
                btnSure.isEnabled = true
            }
        }

    }

    override fun observe() {
        super.observe()

        Bus.observe<DogFileBeanContent>(bus_dog_file_info, this) {
            firstBean = it
            binding.apply {
                btnAddDogInfo.gone()
                btnDogInfo.visible()
                dogId = it.dogId
                dogImg.loadImageCircleCar(it.dogImg)
                dogName.text = it.dogName
                dogType.text = "品种：" + it.dogType + "\n年龄：" + it.age
                afterTextChanged(null)
            }
        }

        mViewModel.anyBean.observe(this) {
            finish()
            Bus.post(bus_toast, ToastBean("绑定成功"))
            if (isFromLogin) {
                SPUtils.getInstance().put("deviceBindDogSuccess", true)
                LoginHelp.isFromLogin = false
                ActivityUtils.startActivity(OneDeviceActivity::class.java)
            }
        }

        mViewModel.mCardNoBean.observe(this) {

            binding.cardNo.text = it?.content?.simNo ?: ""
        }
    }
}